#include <arpa/inet.h>
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>

#define MAX_BUFFER_SIZE 1024

void handleError(const char* message)
{
    fputs(message, stderr);
    fputs("\n", stderr);
    exit(1);
}

int main(int argc, char* argv[])
{

    if (argc != 3)
    {
        printf("Usage: %s <IP> <port>\n", argv[0]);
        exit(0);
    }

    int clientSocket = socket(PF_INET, SOCK_STREAM, 0);
    if (clientSocket == -1)
    {
        handleError("client socket error");
    }

    struct sockaddr_in serverAddress;
    memset(&serverAddress, 0, sizeof(serverAddress));
    serverAddress.sin_family      = AF_INET;
    serverAddress.sin_addr.s_addr = inet_addr(argv[1]);
    serverAddress.sin_port        = htons(atoi(argv[2]));

    if (connect(clientSocket, (struct sockaddr*)(&serverAddress), sizeof(serverAddress)) == -1)
    {
        handleError("connect() error !");
    }
    else
    {
        puts("Connected........");
    }

    while (1)
    {
        fputs("Input message(Q/q to quit): ", stdout);
        char message[MAX_BUFFER_SIZE];
        fgets(message, MAX_BUFFER_SIZE, stdin);

        if (!strcasecmp(message, "q\n"))
        {
            break;
        }
        int messageLength = write(clientSocket, message, strlen(message));

        int receivedLength = 0;
        while (receivedLength < messageLength)
        {
            int length = read(clientSocket, &message[receivedLength], MAX_BUFFER_SIZE - 1);
            if (length == -1)
            {
                handleError("read() error");
            }
            receivedLength += length;
            printf("length = %d , receivedLength = %d\n", length, receivedLength);
        }
        message[receivedLength] = 0;
        printf("Message from server: %s\n", message);
    }
    close(clientSocket);

    return 0;
}